package com.yokead.service.rewrite;

import cn.jiangzeyin.StringUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.odiszapc.nginxparser.NgxBlock;
import com.github.odiszapc.nginxparser.NgxConfig;
import com.github.odiszapc.nginxparser.NgxEntry;
import com.github.odiszapc.nginxparser.NgxParam;
import com.yokead.system.log.SystemLog;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Administrator on 2017/5/11.
 */
@Service
public class ConfService extends RewriteBaseService {
    /**
     * 获取跳转记录
     *
     * @param path
     * @return
     * @throws IOException
     */
    public List<String[]> getRewritesLog(String path) throws IOException {
        File file = new File(path);
        if (!file.exists())
            return null;
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new FileReader(file));
            String line;
            List<String[]> list = new ArrayList<>();
            while ((line = bufferedReader.readLine()) != null) {
                String[] ls = StringUtil.stringToArray(line, ",");
                if (ls == null || ls.length != 5) {
                    continue;
                }
                list.add(ls);
            }
            return list;
        } finally {
            try {
                if (bufferedReader != null)
                    bufferedReader.close();
            } catch (IOException e) {
                SystemLog.ERROR().error("获取错误", e);
            }
        }
    }

    public List<String> getServiceName(String path) throws IOException {
        NgxConfig conf = NgxConfig.read(path);
        NgxParam ngxParam_server = conf.findParam("server", "server_name");//conf.findAll("server_name");
        return ngxParam_server.getValues();
    }

    /**
     * 获取所有跳转信息
     *
     * @param path
     * @param log
     * @return
     * @throws IOException
     */
    public JSONObject getRewrites(String path, boolean log, boolean diff) throws IOException {
        NgxConfig conf = NgxConfig.read(path);
        List<NgxEntry> locations = conf.findAll(NgxConfig.BLOCK, "server", "location");
        if (locations == null || locations.size() <= 0)
            return null;
        List<String[]> rewrites = new ArrayList<>();
        List<String> server_name = null;
        NgxParam ngxParam_server = conf.findParam("server", "server_name");//conf.findAll("server_name");
        if (ngxParam_server != null)
            server_name = ngxParam_server.getValues();
        for (NgxEntry ngxEntry : locations) {
            if (ngxEntry instanceof NgxBlock) {
                NgxBlock block = (NgxBlock) ngxEntry;
                NgxParam ngxParam = block.findParam("rewrite");
                if (ngxParam != null) {
                    String url = ngxParam.getValues().get(1);
                    if (url == null)
                        continue;
                    if (url.endsWith("$2"))
                        url = url.substring(0, url.length() - 2);
                    String[] info = new String[2];
                    info[0] = block.getValue();
                    info[1] = url;
                    rewrites.add(info);
                }
            }
        }
        JSONObject jsonObject = new JSONObject();
        if (log) {
            File conf_file = new File(path);
            String name = conf_file.getName().replace(".conf", ".rewrite_log");
            List<String[]> rewrite_logs = getRewritesLog(new File(conf_file.getParent(), name).getPath());
            if (diff) {
                if (rewrite_logs != null) {
                    Iterator<String[]> iterator = rewrite_logs.iterator();
                    while (iterator.hasNext()) {
                        String[] item = iterator.next();
                        String tag = item[0];
                        for (String[] item_url : rewrites) {
                            if (tag.equals(item_url[0])) {
                                iterator.remove();
                                item_url[0] = item[1] + "," + item[0];
                                break;
                            }
                        }
                    }
                }
            }
            jsonObject.put("rewrite_logs", rewrite_logs);
        }
        jsonObject.put("rewrites", rewrites);
        jsonObject.put("server_name", server_name);
        return jsonObject;
    }
}
